/**
 * 
 */
package org.vsg.security.policy;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.vsg.security.model.domain.SysRole;
import org.vsg.security.vo.SecRole;

/**
 * @author Bill Vison
 *
 */
public class HierarchyRolesHandlerPolicy implements RolesHandlerPolicy {

	/* (non-Javadoc)
	 * @see org.vsg.security.policy.RolesHandlerPolicy#handlePolicy(java.util.Set)
	 */
	@Override
	public Set<SecRole> handlePolicy(Set<SysRole> inputRoles)
			throws HandlerPolicyException {
		// TODO Auto-generated method stub
		Set<SecRole> roles = new HashSet<SecRole>();
		
		filterGrantRoles(inputRoles , roles , 0);
		
		return roles;
	}
	
	
	private void filterGrantRoles(Set<SysRole> inRoles , Set<SecRole> outRoles , int level) {
		SecRole secRole = null;
		SysRole role = null;
		for (Iterator<SysRole> inpIter = inRoles.iterator() ; inpIter.hasNext() ; ) {
			role = inpIter.next();
			
			secRole = new SecRole( role , level);			
			
			if (!role.getDependenceRoles().isEmpty()) {
				int parentLevel = secRole.getLevel();
				filterGrantRoles(role.getDependenceRoles() , outRoles  , ++parentLevel );
			}
			outRoles.add( secRole );
			

			
		}
		
	}

}
